﻿using System.Windows.Forms;
using System.Runtime.InteropServices;
using System;
using ClassMetadataBrowser.Domain;

namespace ClassMetadataBrowser.ToolControls
{
	public enum FocusMode
	{
		SolutionFileSearch,
		MembersSearch
	}

	/// <summary>
	/// Controls that will apear inside of the visual studio toolwindow
	/// </summary>
	[ComVisible(true)]
	[ClassInterface(ClassInterfaceType.AutoDual)]
	[Guid("78666BE0-D7BB-4045-92C1-DCF19999C800")]
	[ProgId("ClassMetadataBrowser.ToolControls.HostControl")]
	public partial class HostControl : UserControl, IHost
	{
		private MembersList _membersList;
		private SolutionFiles _solutionFiles;
		private IMetadataProvider _provider;

		public HostControl()
		{
			InitializeComponent();
		}

		public void SetFocusMode(FocusMode focusMode)
		{
			switch (focusMode)
			{
				case FocusMode.MembersSearch:
					_tabContainer.SelectedTab = _tabCurrentFileMembers;
					break;
				case FocusMode.SolutionFileSearch:
					_tabContainer.SelectedTab = _tabSolutionFiles;
					break;
			}
		}

		protected override void OnLoad(EventArgs e)
		{
			_solutionFiles = new SolutionFiles();
			_solutionFiles.Dock = DockStyle.Fill;
			_tabSolutionFiles.Controls.Add(_solutionFiles);

			_membersList = new MembersList();
			_membersList.HostWindow = this;
			_membersList.Dock = DockStyle.Fill;
			_tabCurrentFileMembers.Controls.Add(_membersList);
		}

		public void AcceptMetadataProvider(IMetadataProvider provider)
		{
			_provider = provider;
			_provider.Rebind += new EventHandler(MetadataRebind);
			_membersList.Bind(provider);
			_solutionFiles.Bind(provider);
		}

		private void MetadataRebind(object sender, EventArgs e)
		{
			this.Invoke(new MetadataLoaded(BindMetadata), sender);
		}

		private void BindMetadata(IMetadataProvider metadataCollection)
		{
			_membersList.Bind(metadataCollection);
		}

		public string FileTitle
		{
			set
			{
				_tabCurrentFileMembers.Text = value;
			}
		}

		#region IHost Members

		void IHost.Close()
		{
			// tool window is not closing...
		}

		#endregion

		private void TabChanged(object sender, EventArgs e)
		{
			if (_tabContainer.SelectedTab == _tabSolutionFiles)
				_solutionFiles.Bind(_provider);
		}
	}
}
